package com.hhhn.wk.main.tab2.view;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;

import com.hhhn.wk.R;
import com.hhhn.wk.base.BaseActivity;
import com.hhhn.wk.config.Config;
import com.hhhn.wk.main.tab2.entity.Commodity;

import com.hhhn.wk.main.tab2.view.xiangqing.activity.CommodityXQActivity;
import com.hhhn.wk.utils.AllPublic;
import com.hhhn.wk.utils.ToastUtils;
import com.hhhn.wk.widget.adapter.MyAdaper;
import com.hhhn.wk.widget.adapter.ViewHolder;
import com.hhhn.wk.widget.wkpulltorefreshlayout.BaseRefreshListener;
import com.hhhn.wk.widget.wkpulltorefreshlayout.PullToRefreshLayout;
import com.hhhn.wk.widget.wkpulltorefreshlayout.ViewStatus;

import org.json.JSONArray;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;

import static com.hhhn.wk.utils.AllPublic.isHuoNiu;

/**
 * 分类-- 列表
 */
public class CommodityListActivity extends BaseActivity {
    private TextView tv_title;
    /*listView*/
    private GridView mLoadListView;
    private PullToRefreshLayout mPullToRefreshLayout;
    public static ArrayList<Commodity> mArrayList=new ArrayList<Commodity>();
    private static MyAdaper<Commodity> mAdapter;
    private int page=1;
    private int refresh = 0;//0 第一次进入  1下拉刷新  2上啦加载
    private boolean isWU = false;
    private String title_str="";
    private String categoryTwo="";
    private Context context;
    private  BaseActivity activity;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    if (mArrayList.size() == 0) {
                        handler.sendEmptyMessage(2);
                    } else {
                        loadData();
                    }
                    break;
                case 2:
                    mPullToRefreshLayout.showView(ViewStatus.EMPTY_STATUS);////空数据
                    dismissLoad();
                    break;
                case 3:
                    mPullToRefreshLayout.showView(ViewStatus.ERROR_STATUS);////网络错误
                    dismissLoad();
                    break;
            }
            super.handleMessage(msg);
        }
    };


    @Override
    protected void setOnCreateContentView() {
        setContentView(R.layout.activity_more_commodity_list);
        context=CommodityListActivity.this;
        activity= this;
        Intent intent=getIntent();
        title_str = intent.getStringExtra("title_str");
        categoryTwo = intent.getStringExtra("categoryTwo");
        Log.d("二级分类进入的列表", "setOnCreateContentView: "+categoryTwo);
    }
    @Override
    protected void initView() {
        tv_title=  findViewById(R.id.tv_title);
        mLoadListView=  findViewById(R.id.mLoadListView);
        mPullToRefreshLayout =  findViewById(R.id.activity_list);
//        mLoadListView.setDivider(new ColorDrawable(getResources().getColor(R.color.colorback)));
    }

    @Override
    protected void initData() {
        tv_title.setText(title_str);
//        switch (type){
//            case 0:
//                tv_title.setText("热销产品");
//                break;
//            case 1:
//                tv_title.setText("特价抢购");
//                break;
//        }

        getJSON();
    }

    @Override
    protected void initClick() {
        mPullToRefreshLayout.setRefreshListener(new BaseRefreshListener() {
            @Override
            public void refresh() {
                upView();
            }
            @Override
            public void loadMore() {
                if (isWU) {
                    ToastUtils.showShortToast(context,"暂无更多");
                    mPullToRefreshLayout.showView(ViewStatus.CONTENT_END);//暂无更多
                } else {
                    refresh = 2;
                    page++;
                    if (mAdapter!=null){
                        mAdapter.notifyDataSetChanged();
                    }
                    getJSON();
                }
            }
        });
        mLoadListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent=new Intent(context,CommodityXQActivity.class);
                intent.putExtra("goods_id",mArrayList.get(i).getCommodityID());
                startActivity(intent);
            }
        });

    }
    private void upView(){
        refresh = 1;
        page = 1;
        mArrayList.clear();
        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
        }
        isWU = false;
        getJSON();
    }



    public void getJSON() {
        showLoad();
        RequestParams  params = AllPublic.getParamsType(activity, "/getProduct", false);
        params.addParameter("categoryTwo",categoryTwo);
        params.addParameter("currentPage",page);
        params.addParameter("pageSize", Config.ROWS);
        Log.d("分类列表", "getJSON: "+params);
        //请求
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override  //成功
            public void onSuccess(String result) {
                Log.d("分类列表：", result);
                try {
                    JSONObject jsonObject= new JSONObject(result);
                    String reason = jsonObject.getString("code");
                    if (reason.equals("0")) {
                        JSONArray records = jsonObject.getJSONArray("data");
                        Commodity commodity=null;
                        if (records.length()< Config.ROWS){
                            isWU=true;
                        }
                        for (int i=0;i<records.length();i++){

                            commodity=new Commodity();
                            JSONObject object = records.getJSONObject(i);
                            String commodityid = object.has("id") ? object.getString("id") : "";//id
                            String image = object.has("productPicture") ? object.getString("productPicture") : "";//产品图片
                            String headLine = object.has("name") ? object.getString("name") : "";//产品名称
                            String tradeprice = object.has("wholesalePriceThree") ? object.getString("wholesalePriceThree") : "";//新价格-折扣价格
                            String originalprice = object.has("originalPrice") ? object.getString("originalPrice") : "";//原价-旧价格
                            String inventory = object.has("inventory") ? object.getString("inventory") : "";//商品库存-剩余库存
                            commodity.setCommodityID(commodityid);
                            commodity.setCommodityImg(image);
                            commodity.setCommodityName(headLine);
                            commodity.setPriceOld(originalprice);
                            commodity.setPriceNew(tradeprice);
                            commodity.setInventoryNumber(inventory);
                            mArrayList.add(commodity);
                        }
                        handler.sendEmptyMessage(1);
                    }else {
                        toastWk(jsonObject.getString(getResources().getString(R.string.errMsg)));
                    }
                } catch (Exception e) {
                    e.printStackTrace();

                }
                dismissLoad();
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

                ex.printStackTrace();
                dismissLoad();
            }
            @Override
            public void onCancelled(CancelledException cex) {

                dismissLoad();
            }
            @Override
            public void onFinished() {

                dismissLoad();
            }
        });
    }
    private void loadData() {
        if (mAdapter==null){
            mAdapter=new MyAdaper<Commodity>(mArrayList,R.layout.item_commoditylist) {
                @Override
                public void bindView(ViewHolder holder, Commodity obj, int position) {
                    holder.setImageyuan(R.id.iv_CommodityImg,obj.getCommodityImg());//图片
                    holder.setText(R.id.iv_CommodityName,obj.getCommodityName());

                    if (isHuoNiu(activity)){
                        holder.setText(R.id.tv_priceNew,"￥"+obj.getPriceNew());
                        holder.setFlags(R.id.tv_priceOld,"￥"+obj.getPriceOld());
                    }else {
                        holder.setText(R.id.tv_priceNew,"￥?");
                        holder.setFlags(R.id.tv_priceOld,"￥?");
                    }
                    holder.setText(R.id.tv_inventoryNumber,"剩余："+obj.getInventoryNumber());
                }
            };
            mLoadListView.setAdapter(mAdapter);
        }else {
            mAdapter.notifyDataSetChanged();
        }
        if (refresh == 1) {
            mPullToRefreshLayout.finishRefresh();//下拉刷新
        } else if (refresh == 2) {
            mPullToRefreshLayout.finishLoadMore();//上啦加载
        }
        dismissLoad();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mArrayList!=null){
            mArrayList.clear();
        }
        if (mAdapter!=null){
            mAdapter=null;
        }
    }
}
